package com.motionlog.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.motionlog.R;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class Mp3Player extends ListActivity implements OnClickListener {

/** Called when the activity is first created. */
/* 定义5个图像按钮 */
private ImageButton    mFrontImageButton    = null;
private ImageButton    mStartImageButton    = null;
private ImageButton    mPauseImageButton    = null;
private ImageButton    mStopImageButton    = null;
private ImageButton    mNextImageButton    = null;

/*定义进度handler，显示百分比进度*/
Handler mPercentHandler = new Handler();

/*定义拖动条*/
private SeekBar     mSeekBar=null;

/*定义显示文本框*/
private TextView curProgressText=null;
private TextView curtimeAndTotaltime=null;

/* 定于一个多媒体对象*/
public MediaPlayer    mMediaPlayer        = null;

/*定于一个数据播放列表，用来存放从指定文件中搜索到的文件*/
private List<String> mMusicList = new ArrayList<String>();

/* 定义在播放列表中的当前选择项 */
private int currentListItme = 0;

/*定义要播放的文件夹路径 此处 需要设置MP3在设备上的路径*/ 
private static final String MUSIC_PATH = new String("/mnt/sdcard/wandoujia/music/");

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.musicplayer);
/* 更新播放列表*/
musicList();
/*初始化多媒体对象*/
mMediaPlayer        = new MediaPlayer();

/*初始化图像按钮*/
mFrontImageButton = (ImageButton) findViewById(R.id.LastImageButton); 
mStopImageButton =  (ImageButton) findViewById(R.id.StopImageButton);
mStartImageButton = (ImageButton) findViewById(R.id.StartImageButton); 
mPauseImageButton = (ImageButton) findViewById(R.id.PauseImageButton);
mNextImageButton = (ImageButton) findViewById(R.id.NextImageButton); 

/*初始化拖动条和当前进度显示值*/
mSeekBar=(SeekBar)findViewById(R.id.SeekBar01);
curProgressText=(TextView)findViewById(R.id.currentProgress);
curtimeAndTotaltime=(TextView)findViewById(R.id.curtimeandtotaltime);

/*监听停止按钮*/
mStopImageButton.setOnClickListener(new ImageButton.OnClickListener() 
{
@Override
public void onClick(View v)
{
/*判断是否正在播放歌曲*/
if (mMediaPlayer.isPlaying())
{
/*如果在播放歌曲时，按下开始按钮，则重开开始播放*/
mMediaPlayer.reset();
}
}
}); 

/*监听开始按钮*/
mStartImageButton.setOnClickListener(new ImageButton.OnClickListener() 
{
@Override
public void onClick(View v)
{   /*播放当前选择歌曲，通过listView列表中onListItemClick方法得到选择的时第几项*/
playMusic(MUSIC_PATH + mMusicList.get(currentListItme));
/*开始播放歌曲时，同步进行更新拖动条进度*/
startSeekBarUpdate();
}    
});  

/*监听暂停按钮*/
mPauseImageButton.setOnClickListener(new ImageButton.OnClickListener() 
{
public void onClick(View view)
{
if (mMediaPlayer.isPlaying())
{
/*如果有播放歌曲，暂停*/
mMediaPlayer.pause();
}
else 
{
/*如果没有播放歌曲，则开始播放*/
mMediaPlayer.start();
}
}
});

/*监听下一首按钮*/
mNextImageButton.setOnClickListener(new ImageButton.OnClickListener() 
{
@Override
public void onClick(View arg0)
{   
nextMusic();
}
});
/*监听上一首按钮*/
mFrontImageButton.setOnClickListener(new ImageButton.OnClickListener() 
{
@Override
public void onClick(View arg0)
{
FrontMusic();
}
});

/*监听拖动条*/
mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{                                        

public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
/*如果拖动进度发生改变，则显示当前进度值*/
curProgressText.setText("当前进度: "+progress);    
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
curProgressText.setText("拖动中...");
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int dest = seekBar.getProgress();    
int mMax = mMediaPlayer.getDuration();
int sMax = mSeekBar.getMax();

mMediaPlayer.seekTo(mMax*dest/sMax);

}
}
);



}

/*按键处理时间,当按下返回按键时的处理方法*/
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ( keyCode ==  KeyEvent.KEYCODE_BACK)
{
mMediaPlayer.stop();
mMediaPlayer.release();
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}

/*ListView选择项监听方法，即当前鼠标在列表中选择的第几项*/
protected void onListItemClick(ListView l, View v, int position, long id)
{
currentListItme = position;
playMusic(MUSIC_PATH + mMusicList.get(position));
}


/*更新播放列表*/
public void musicList()
{
/*从指定的路径中读取文件，并与播放列表关联*/
File home = new File(MUSIC_PATH);
/*读取指定类型的文件，在本程序，指定播放类型为mp3*/
if (home.listFiles(new MusicFilter()).length > 0)
{
/*读取文件*/
for (File file : home.listFiles(new MusicFilter()))
{
mMusicList.add(file.getName());
}
/*播放文件与播放列表关联*/
ArrayAdapter<String> musicList = new ArrayAdapter<String>(Mp3Player.this,R.layout.musictime, mMusicList);
setListAdapter(musicList);
}
}
/*播放指定路径中的音乐*/
private void playMusic(String path)
{
try
{
/* 重置多媒体 */
mMediaPlayer.reset();
/*读取mp3文件*/
mMediaPlayer.setDataSource(path);
/*准备播放*/
mMediaPlayer.prepare();
/*开始播放*/
mMediaPlayer.start();
/*监听播放是否完成*/
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() 
{
public void onCompletion(MediaPlayer arg0)
{
/*播放完当前歌曲，自动播放下一首*/
nextMusic();
}
});
}catch (IOException e){}
}

/*播放下一首*/
private void nextMusic()
{
if (++currentListItme >= mMusicList.size())
{
currentListItme = 0;
}
else
{
playMusic(MUSIC_PATH + mMusicList.get(currentListItme));
}
}



/*播放上一首歌曲*/
private void FrontMusic()
{
if (--currentListItme >= 0)
{
currentListItme = 0;
}
else
{
playMusic(MUSIC_PATH + mMusicList.get(currentListItme));
}
}

/*更新拖动条进度*/

public void startSeekBarUpdate()
{
mPercentHandler.post(start);
}

Runnable start=new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
mPercentHandler.post(updatesb);
//用一个handler更新SeekBar
}

};

Runnable updatesb =new Runnable(){

@Override
public void run() {
// TODO Auto-generated method stub
int position = mMediaPlayer.getCurrentPosition();               
int mMax = mMediaPlayer.getDuration();
int sMax = mSeekBar.getMax();             
mSeekBar.setProgress(position*sMax/mMax);
curtimeAndTotaltime.setText("当前播放时间： "+position/1000+"秒"+"\n歌曲总时间: "+mMax/1000+"秒");
mPercentHandler.postDelayed(updatesb, 1000);
//每秒钟更新一次
}

};

@Override
public void onClick(View arg0) {
	// TODO Auto-generated method stub
	
}

}

/*播放文件选择类*/
class MusicFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
/*指定扩展名类型*/
return (name.endsWith(".mp3"));
}
}